import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router";
import { App } from "vue";
import store from "../store";
import Cookies from "js-cookie";
import { getAdminInfoApi } from "../request/api";
const routes: RouteRecordRaw[] = [
    {
        path: '/login',
        name: 'login',
        component: () => import('../views/login/login.vue')
    },
    {
        path: '/homepage',
        name: 'homepage',
        component: () => import('../views/homepage/homepage.vue')
    },


    // {
    //     path: '/pms',
    //     name: 'pms',
    //     component: () => import('../views/homepage/homepage.vue'),
    //     children: [
    //         {
    //             path: '/product',
    //             name: 'product',
    //             component: () => import('../views/pms/product.vue')
    //         },
    //         {
    //             path: '/addProduct',
    //             name: 'addProduct',
    //             component: () => import('../views/pms/addProduct.vue')
    //         },
    //     ]
    // },
]

const router = createRouter({
    history: createWebHashHistory(),
    // 路由配置
    routes
})

// 前置路由守卫
router.beforeEach((to, from, next) => {
    // token存在并且menus里面为空数组
    const token = Cookies.get('token')
    if (token && store.state.menus.length == 0) {
        console.log('刷新后,menus为空,重新获取数据');
        // getAdminInfoApi().then(res => {
        //     if (res.code == 200) {
        //         store.commit('updateMenus', res.data.menus)
        //         console.log(store.state.menus);
        //     }
        // })
        store.dispatch('getAdminInfo').then(() => {
            const menus = store.getters.getNewMenus
            // const newRoutes: RouteRecordRaw[] = []
            // 循环菜单对象
            for (let key in menus) {
                const newRoute: RouteRecordRaw = {
                    path: '/' + menus[key].name,
                    name: menus[key].name,
                    component: () => import('../views/homepage/homepage.vue'),
                    redirect: '/' + menus[key].name + '/' + menus[key].children[0].name,
                    children: []
                };
                for (let i = 0; i < menus[key].children.length; i++) {
                    newRoute.children?.push({
                        path: menus[key].children[i].name,
                        name: menus[key].children[i].name,
                        component: () => import(`../views/${menus[key].name}/${menus[key].children[i].name}.vue`)
                    })
                }

                // 动态添加路由规则
                router.addRoute(newRoute)
            }
        })

    }
    next()
})

export const initRouter = (app: App<Element>) => {
    app.use(router)
}